package com.guang.springbootscheduleexecutortest.distributedlock.db;

import com.guang.springbootscheduleexecutortest.distributedlock.DistributedLock;
import com.guang.springbootscheduleexecutortest.distributedlock.db.biz.DataBaseDistributedLockBiz;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author lg
 * @Description
 * @date 2022/11/4 17:27
 */
@Component
public class DataBaseDistributedLock implements DistributedLock {

    private static final Logger logger = LoggerFactory.getLogger(DataBaseDistributedLock.class);

    private static final long lockTimeOut = 3000L;


    @Resource
    private DataBaseDistributedLockBiz dataBaseDistributedLockBiz;

    @Override
    public void lock(String lockKey) {
        if (!validateLockKey(lockKey)) {
            logger.error("分布式锁lockKey为空");
            throw new IllegalArgumentException("分布式锁lockKey为空");
        } else {
            while (true) {
                try {
                    if (tryLock(lockKey)) {
                        return;
                    }
                    sleep(50L);
                } catch (Throwable t) {
                    sleep(50L);
                }
            }
        }
    }


    @Override
    public boolean tryLock(String lockKey) {
        if (!validateLockKey(lockKey)) {
            logger.error("分布式锁lockKey有问题");
            throw new IllegalArgumentException("分布式锁lockKey为空");
        } else {
            // TODO：首先应该先来检查当前线层是否已经持有了锁，为了方便可重入
            String uuid = getUUID();
            if (dataBaseDistributedLockBiz.tryLock(lockKey,uuid,lockTimeOut)){

            }

            return false;
        }
    }

    @Override
    public boolean tryLock(String lockKey, long timeOut, TimeUnit timeUnit) {
        return false;
    }

    @Override
    public void unlock() {

    }

    /**
     * 检测lcokKey是否合理
     *
     * @param lockKey 分布式锁key
     * @return
     */
    private boolean validateLockKey(String lockKey) {
        return StringUtils.hasText(lockKey);
    }

    public void sleep(long lockKeyOut) {
        try {
            Thread.sleep(lockKeyOut);
        } catch (InterruptedException e) {

        }
    }


    /**
     * 返回UUID
     * @return
     */
    private String getUUID(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

}
